# encoding: utf-8
class AdvertiseGroup < ActiveRecord::Base
  has_paper_trail :version => :paper_trail_version, :versions => :paper_trail_versions
  has_many :advertises,:order => 'created_at asc', dependent: :destroy
  attr_accessible :name,:start_at,:end_at
  validates :name, :presence => true, :uniqueness => true
  has_many :province_advertise_rules, :class_name => "AdvertiseRule", :conditions => "advertise_ruleable_type = 'Province'", dependent: :destroy
  has_many :city_advertise_rules, :class_name => "AdvertiseRule", :conditions => "advertise_ruleable_type = 'City'" , dependent: :destroy
  has_many :terminal_group_advertise_rules, :class_name => "AdvertiseRule", :conditions => "advertise_ruleable_type = 'TerminalGroup'" , dependent: :destroy
  after_create :create_advertises

  def display_advertise_rules
    output = ""
    if self.terminal_group_advertise_rules.present?
      output = "设备组: "
      output << self.terminal_group_advertise_rules.map{|i| i.advertise_ruleable.try(:group_name) }.join(', ')
      output << "<p>"
    end
    if self.city_advertise_rules.present?
      output << "城市: "
      output << self.city_advertise_rules.map{|i| i.advertise_ruleable.try(:name) }.join(', ')
      output << "<p>"
    end
    if self.province_advertise_rules.present?
      output << "省: "
      output << self.province_advertise_rules.map{|i| i.advertise_ruleable.try(:name) }.join(', ')
    end
    output
  end

  private

  def create_advertises
    %w{启动页面 签到前 签到后 视频播放前 保留位1 保留位2}.each do |position|
      self.advertises.create!(position: position)
    end
  end

end
